package com.zhbcm.outupload.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.zhbcm.outupload.config.UploadProperties;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2021/6/28 23:22
 */
@Service
public class UploadFileUtil
{
    private static final Logger log = LoggerFactory.getLogger(UploadFileUtil.class);
    private final String FORMAT = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

    @Autowired
    private UploadProperties uploadProperties;

    /**
     * 上传
     *
     * @param file 网络文件传输
     * @param req
     * @return
     */
    public String upload(MultipartFile file, HttpServletRequest req)
    {
        File folder = new File(uploadProperties.getFileLocation() + FORMAT);
        if (!folder.isDirectory() && !folder.mkdirs())
        {
            return "文件夹创建失败";
        }
        String oldName = file.getOriginalFilename();
        assert oldName != null;
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
        try
        {
            file.transferTo(new File(folder, newName));
            //以上都是普通代码, 这里的/files/ 对应的就是你在WebMvcConfig设置的地址映射
            return req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort()
                    + uploadProperties.getResourceHandler() + FORMAT + "/" + newName;
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        return "上传失败！";
    }

    /**
     * 上传
     *
     * @param file 本地文件传输
     * @param req
     * @return
     */
    public String upload(File file, HttpServletRequest req)
    {
        File folder = new File(uploadProperties.getFileLocation() + FORMAT);
        if (!folder.isDirectory() && !folder.mkdirs())
        {
            return "文件夹创建失败";
        }
        String oldName = file.getName();
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
        FileUtil.copy(file, new File(folder, newName), false);
        //以上都是普通代码, 这里的/files/ 对应的就是你在WebMvcConfig设置的地址映射
        return req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort()
                + uploadProperties.getResourceHandler() + FORMAT + "/" + newName;
    }

    /**
     * 下载
     *
     * @param url      网络地址 http://localhost:8080/files/2021-06-29/5c8ec19a-7cfa-46d2-9310-a9197b3fb0b7.jpg
     * @param response
     */
    public void downloadImg(String url, HttpServletResponse response)
    {
        try
        {
            URL url1 = new URL(url);
            URLConnection urlConnection = url1.openConnection();
            String ext = url.substring(url.lastIndexOf("."));
            String contentType = getContentType(url);
            response.setContentType(contentType);
            response.setHeader("Content-Disposition", "attachment;filename=" + IdUtil.simpleUUID() + ext);
            InputStream is = urlConnection.getInputStream();
            OutputStream os = response.getOutputStream();
            IOUtils.copy(is, os);
            os.flush();
            os.close();
            is.close();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 方式二
     * 该方式支持本地文件，也支持http/https远程文件
     *
     * @param fileUrl
     */
    private static String getContentType(String fileUrl)
    {
        String contentType = null;
        try
        {
            contentType = new MimetypesFileTypeMap().getContentType(new File(fileUrl));
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        log.info("getContentType, File ContentType is : {} " + contentType);
        return contentType;
    }
}
